import { storageService } from './storage.service';

class AuthService {
    constructor() {
        this.localStorage = storageService;
    }

    isLogin() {
        return this.getToken()?.length > 10;
    }

    getToken() {
        return this.localStorage.getValue('token');
    }

    setToken(token) {
        this.localStorage.setValue('token', token);
    }

    clearToken() {
        this.localStorage.clearValue('token');
    }

    getUser() {
        const user = this.localStorage.getValue('user-information');
        return user ? JSON.parse(user) : null;
    }

    setUser(user) {
        this.localStorage.setValue('user-information', JSON.stringify(user));
    }

    async login(httpService, email, password) {
        const response = await httpService.post('user/login',
            { email, password },
            { requireAuth: false }
        );
        if (response.token) {
            this.setToken(response.token);
            this.setUser(response);
        }
        return response;
    }

    logout() {
        this.clearToken();
    }
}

export const authService = new AuthService();